Different Ways to Add Parentheses

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.

Example 1

Input: "2-1-1".

  1. ((2-1)-1) = 0
  2. (2-(1-1)) = 2

Output: [0, 2]

Example 2

Input: "2*3-4*5"

  1. (2*(3-(4*5))) = -34
  2. ((2*3)-(4*5)) = -14
  3. ((2*(3-4))*5) = -10
  4. (2*((3-4)*5)) = -10
  5. (((2*3)-4)*5) = 10

Output: [-34, -14, -10, -10, 10]

Solution:

  1. public class Solution {
  2. public List<Integer> diffWaysToCompute(String input) {
  3. List<Integer> res = new ArrayList<Integer>();
  4. for (int i = 1; i < input.length(); i++) {
  5. char c = input.charAt(i);
  6. if (c == '+' || c == '-' || c == '*') {
  7. String s1 = input.substring(0, i);
  8. String s2 = input.substring(i + 1);
  9. List<Integer> l1 = diffWaysToCompute(s1);
  10. List<Integer> l2 = diffWaysToCompute(s2);
  11. for (Integer n1 : l1) {
  12. for (Integer n2 : l2) {
  13. switch (c) {
  14. case '+': res.add(n1 + n2); break;
  15. case '-': res.add(n1 - n2); break;
  16. case '*': res.add(n1 * n2); break;
  17. }
  18. }
  19. }
  20. }
  21. }
  22. if (res.size() == 0) {
  23. res.add(Integer.valueOf(input));
  24. }
  25. return res;
  26. }
  27. }